package com.substation.ui.fragment;

import android.content.Intent;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.greenentity.Inspect;
import com.greenentity.Unit;
import com.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.substation.R;
import com.substation.greendao.InspectDao;
import com.substation.ui.activity.DefectAddActivity;
import com.substation.ui.utils.RecyclerViewUtils;
import com.substation.utils.DateUtils;
import com.substation.utils.DialogUtils;
import com.substation.utils.GreenDaoManager;
import com.substation.utils.SPUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2018/5/17.
 * 巡检
 */

public class InspectionFragment extends BaseFragment {
    @BindView(R.id.list)
    RecyclerView list;
    SuperAdapter<Inspect> adapter;
    List<Inspect> datas = new ArrayList<>();
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.complete)
    TextView complete;
    @BindView(R.id.totalCount)
    TextView totalCount;
    @BindView(R.id.readCount)
    TextView readCount;
    Unit unit;
    int total = 0;
    int ready = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_inspection;
    }

    @Override
    protected void initView() {
        list.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        list.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        list.setAdapter(adapter = new SuperAdapter<Inspect>(R.layout.content_inspection) {
            @Override
            public void bindView(final ViewHolder viewHolder, final Inspect inspect, final int i) {
                ((TextView) viewHolder.getView(R.id.number)).setText(inspect.getSortNo() + "");
                ((TextView) viewHolder.getView(R.id.content)).setText(inspect.getTourItem());
                ((TextView) viewHolder.getView(R.id.bz_content)).setText(inspect.getContent());
                final TextView zc = viewHolder.getView(R.id.radioButton1);
                final TextView yc = viewHolder.getView(R.id.radioButton2);
                if (inspect.getMarkTime() != null && !inspect.getMarkTime().equals("")) {
                    if (inspect.getConclusion() != null && !inspect.getConclusion().equals("")) {
                        if (inspect.getConclusion().equals("00")) {
                            zc.setBackgroundResource(android.R.color.holo_green_dark);
                            yc.setBackgroundResource(R.color.white);
                        } else if (inspect.getConclusion().equals("10")) {
                            zc.setBackgroundResource(R.color.white);
                            yc.setBackgroundResource(android.R.color.holo_red_dark);
                        }
                    }
                } else {
                    zc.setBackgroundResource(R.color.white);
                    yc.setBackgroundResource(R.color.white);
                }
                zc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (inspect.getMarkTime() != null && !inspect.getMarkTime().equals("")
                                && inspect.getConclusion() != null && inspect.getConclusion().equals("00")) {
                            return;
                        }
                        if (inspect.getDefectCount() > 0) {
                            showMsg("该项有新建缺陷，删除自动设置为正常");
                            return;
                        }
                        if (inspect.getMarkTime() != null && !inspect.getMarkTime().equals("")
                                && inspect.getConclusion() != null && inspect.getConclusion().equals("10")) {
                            unit.setExcount(unit.getExcount() - 1);
                            SPUtils.put(context, "unit", JSON.toJSONString(unit));
                            GreenDaoManager.getInstance().getmDaoSession().getUnitDao().update(unit);
                        }
                        zc.setBackgroundResource(android.R.color.holo_green_dark);
                        yc.setBackgroundResource(R.color.white);
                        inspect.setMarkTime(DateUtils.getNewTime());
                        inspect.setConclusion("00");
                        GreenDaoManager.getInstance().getmDaoSession().getInspectDao().update(inspect);
                        setUnit();
                    }
                });
                yc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (inspect.getMarkTime() != null && !inspect.getMarkTime().equals("")
                                && inspect.getConclusion() != null && inspect.getConclusion().equals("10")) {

                        } else {
                            unit.setExcount(unit.getExcount() + 1);
                            SPUtils.put(context, "unit", JSON.toJSONString(unit));
                            GreenDaoManager.getInstance().getmDaoSession().getUnitDao().update(unit);
                        }
                        zc.setBackgroundResource(R.color.white);
                        yc.setBackgroundResource(android.R.color.holo_red_dark);
                        inspect.setMarkTime(DateUtils.getNewTime());
                        inspect.setConclusion("10");
                        GreenDaoManager.getInstance().getmDaoSession().getInspectDao().update(inspect);
                        setUnit();
                        SPUtils.put(context, "defect_content", unit.getTourUnit() + "---" + inspect.getTourItem());
                        SPUtils.put(context, "inspect", JSON.toJSONString(inspect));
                        Intent intent = new Intent(context, DefectAddActivity.class);
                        intent.putExtra("inspect", true);
                        startActivity(intent);
                    }
                });
                final TextView result = viewHolder.getView(R.id.result);
                result.setMovementMethod(ScrollingMovementMethod.getInstance());
                if (inspect.getRecordMode().equals("1")) {
                    viewHolder.getView(R.id.result_layout).setVisibility(View.VISIBLE);
                    result.setText(inspect.getMarkValue() == null ? "" : inspect.getMarkValue());
                    View.OnClickListener listener = new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String t = inspect.getTourItem();
                            String title = "";
                            if (t.contains("【") && t.contains("】")) {
                                title = t.substring(0, t.indexOf("【"));
                                String c = t.substring(t.indexOf("【") + 1, t.lastIndexOf("】"));
                                DialogUtils.showListEditTextDialog(getActivity(), title, inspect.getMarkValue() == null ? "" : inspect.getMarkValue(), Arrays.asList(c.split("：")), new ResponseListener<String>() {
                                    @Override
                                    public void response(String data) {
                                        result.setText(data);
                                        inspect.setMarkValue(data);
                                        GreenDaoManager.getInstance().getmDaoSession().getInspectDao().update(inspect);
                                    }
                                });
                            } else {
                                title = t;
                                DialogUtils.showEditTextInspectionDialog(context, title, new ResponseListener<String>() {
                                    @Override
                                    public void response(String data) {
                                        result.setText(data);
                                        inspect.setMarkValue(data);
                                        GreenDaoManager.getInstance().getmDaoSession().getInspectDao().update(inspect);
                                    }
                                });
                            }
                        }
                    };
                    result.setOnClickListener(listener);
                } else {
                    result.setClickable(false);
                    viewHolder.getView(R.id.result_layout).setVisibility(View.GONE);
                }
            }
        });
        adapter.setData(datas);
        setDatas();
    }

    public void setDatas() {
        datas.clear();
        unit = JSON.parseObject((String) SPUtils.get(context, "unit", ""), Unit.class);
        name.setText(unit.getTourUnit());
        datas.addAll(GreenDaoManager.getInstance().getmDaoSession().getInspectDao().queryBuilder().where(InspectDao.Properties.UnitGuid.eq(unit.getUnitGuid())).orderAsc(InspectDao.Properties.SortNo).list());
        total = datas.size();
        adapter.notifyDataSetChanged();
        setUnit();
    }

    @OnClick(R.id.seeAll)
    public void onViewClicked() {
        String result = "";
        for (Inspect inspect : datas) {
            if (TextUtils.isEmpty(inspect.getMarkTime())) {
                if (inspect.getRecordMode().equals("1") && TextUtils.isEmpty(inspect.getMarkValue())) {
                    result += "第" + inspect.getSortNo() + "项.";
                } else {
                    inspect.setMarkTime(DateUtils.getNewTime());
                    inspect.setConclusion("00");
                }
            }
        }
        GreenDaoManager.getInstance().getmDaoSession().getInspectDao().updateInTx(datas);
        adapter.notifyDataSetChanged();
        setUnit();
        if (!TextUtils.isEmpty(result)) {
            showMsg(result + "需要输入巡捡结果");
        }
    }

    void setUnit() {
        ready = 0;
        for (Inspect inspect : datas) {
            if (inspect.getMarkTime() != null && !inspect.getMarkTime().equals("")) {
                ready++;
            }
        }
        if (ready == total) {
            unit.setComplete(1);
            GreenDaoManager.getInstance().getmDaoSession().getUnitDao().update(unit);
            SPUtils.put(context, "unit", JSON.toJSONString(unit));
        }
        setStatus();
    }

    void setStatus() {
        complete.setText(unit.getComplete() == 0 ? "(未完成)" : "(已完成)");
        totalCount.setText(total + "");
        readCount.setText(ready + "");
    }
}
